<!--
* @Author: your name
* @Date: 2020-11-11 09:49:59
 * @LastEditTime: 2020-11-11 11:25:40
 * @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \vue_plugins\src\views\chat\websocket.vue
-->
<template>
<div class="container">
    <van-nav-bar title="websocket聊天" :border="false" left-arrow fixed @click-left="$router.go('-1')" />
    <van-field
    v-model="msg"
    center
    clearable
    label="消息"
    placeholder="请输入消息"
    >
    <template #button>
        <van-button size="small" type="primary" @click.stop="Send">发送</van-button>
    </template>
    </van-field>
</div>
</template>

<script>
export default {
    data(){
        return{
            ws:'',
            msg:''
        }
    },
    mounted(){
        this.init();
    },
    beforeDestroy(){
        this.ws.close();
    },
    methods:{
        init(){
            this.ws = new WebSocket("ws://kz.xiachunlong.cn:8282");
            let ws = this.ws;
            ws.onopen = function(evt) { 
            console.log("Connection open ..."); 
                ws.send("Hello WebSockets!");
            };
            
            ws.onmessage = function(evt) {
                console.log( "Received Message: " + evt.data);
                // ws.close();
            };
            
            ws.onclose = function(evt) {
                console.log("Connection closed.");
            };
        },
        Send(){
            this.ws.send({message:this.msg})
        }
    }
}
</script>

<style lang="less" scoped>

</style>